package com.tomek.ktoryoperator.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class NetworkProviderContentProvider extends ContentProvider {

	private static final String CONTENT_ALL_ENTRIES_URI_STRING = "content://com.tomek.ktoryoperator/operators";
	private static final String CONTENT_ENTRY_BY_ID_URI_STRING = "content://com.tomek.ktoryoperator/operators/#";
	private static final String CONTENT_ENTRY_BY_NUMBER_URI_STRING = "content://com.tomek.ktoryoperator/operators/numbers/#";

	public static final Uri CONTENT_ALL_ENTRIES_URI = Uri.parse(CONTENT_ALL_ENTRIES_URI_STRING);
	public static final Uri CONTENT_ENTRY_BY_ID_URI = Uri.parse(CONTENT_ENTRY_BY_ID_URI_STRING);
	public static final Uri CONTENT_ENTRY_BY_NUMBER_URI = Uri.parse(CONTENT_ENTRY_BY_NUMBER_URI_STRING);

	private static final int ALL_ENTRIES = 1;
	private static final int ENTRY_BY_ID = 2;
	private static final int ENTRY_BY_NUMBER = 3;

	private static final UriMatcher uriMatcher;

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

		uriMatcher.addURI("com.tomek.ktoryoperator", "operators", ALL_ENTRIES);
		uriMatcher.addURI("com.tomek.ktoryoperator", "operators/#", ENTRY_BY_ID);
		uriMatcher.addURI("com.tomek.ktoryoperator", "operators/numbers/#", ENTRY_BY_NUMBER);
	}

	private static final String DATABASE_NAME = "data";
	private static final String NUMBERS_TABLE = "numbers";
	private static final int DATABASE_VERSION = 3;

	public static final String KEY_ID = "_id";
	public static final String KEY_NUMBER = "number";
	public static final String KEY_PROVIDER = "provider";
	public static final String KEY_VALUE = "value";
	public static final String KEY_DATE = "date";

	public static final int COLUMN_ID = 0;
	public static final int COLUMN_NUMBER = 1;
	public static final int COLUMN_PROVIDER = 2;
	public static final int COLUMN_VALUE = 3;
	public static final int COLUMN_DATE = 4;

	private SQLiteDatabase db;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_CREATE = "create table " + NUMBERS_TABLE + " (" + KEY_ID
				+ " integer primary key autoincrement, " + KEY_NUMBER + " text not null, " + KEY_PROVIDER
				+ " text not null, " + KEY_VALUE + " text, " + KEY_DATE + " integer);";

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + NUMBERS_TABLE);
			onCreate(db);
		}
	}

	@Override
	public boolean onCreate() {
		Context c = getContext();

		DatabaseHelper dh = new DatabaseHelper(c);
		db = dh.getWritableDatabase();

		return (db == null) ? false : true;
	}

	@Override
	public String getType(Uri uri) {
		switch (uriMatcher.match(uri)) {
		case ALL_ENTRIES:
			return "vnd.android.cursor.dir/com.tomek.ktoryoperator";
		case ENTRY_BY_ID:
			return "vnd.android.cursor.item/com.tomek.ktoryoperator";
		case ENTRY_BY_NUMBER:
			return "vnd.android.cursor.item/com.tomek.ktoryoperator";
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(NUMBERS_TABLE);

		switch (uriMatcher.match(uri)) {
		case ENTRY_BY_ID:
			qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
			break;
		case ENTRY_BY_NUMBER:
			qb.appendWhere(KEY_NUMBER + "=" + uri.getPathSegments().get(2));
			break;
		default:
			break;
		}

		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);

		return c;
	}

	@Override
	public int delete(Uri _uri, String where, String[] whereArgs) {
		int count;

		switch (uriMatcher.match(_uri)) {
		case ALL_ENTRIES:
			count = db.delete(NUMBERS_TABLE, where, whereArgs);
			break;
		case ENTRY_BY_ID:
			String segment = _uri.getPathSegments().get(1);
			count = db.delete(NUMBERS_TABLE, KEY_ID + "=" + segment
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unsupported URI: " + _uri);
		}

		// getContext().getContentResolver().notifyChange(_uri, null);
		return count;
	}

	@Override
	public Uri insert(Uri _uri, ContentValues values) {
		long rowID = db.insert(NUMBERS_TABLE, null, values);

		if (rowID > 0) {
			Uri uri = ContentUris.withAppendedId(CONTENT_ALL_ENTRIES_URI, rowID);
			getContext().getContentResolver().notifyChange(uri, null);
			return uri;
		}

		throw new SQLException("Failed to insert row into " + _uri);
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		int count;
		switch (uriMatcher.match(uri)) {
		case ALL_ENTRIES:
			count = db.update(NUMBERS_TABLE, values, where, whereArgs);
			break;
		case ENTRY_BY_ID:
			String id = uri.getPathSegments().get(1);
			count = db.update(NUMBERS_TABLE, values, KEY_ID + "=" + id
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;
		case ENTRY_BY_NUMBER:
			String number = uri.getPathSegments().get(1);
			count = db.update(NUMBERS_TABLE, values, KEY_NUMBER + "=" + number
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);

		return count;
	}
}